package com.foreveross.bsl.push.web.controllers;

import java.io.IOException;
import java.io.InputStream;

import javax.inject.Inject;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.foreveross.bsl.common.utils.web.QuerySpecs;
import com.foreveross.bsl.push.application.AppChannelConfigService;
import com.foreveross.bsl.push.application.vo.AppChannelConfigVo;
import com.foreveross.bsl.push.web.PageMustache;
import com.foreveross.bsl.push.web.controllers.form.AppChannelConfigForm;
import com.foreveross.bsl.push.web.controllers.form.AppChannelConfigForm.ApnsConfigForm;
import com.foreveross.bsl.push.web.controllers.form.AppChannelConfigForm.OpenfireConfigForm;

/**
 * 
 * @description
 * 
 * @author Wangyi
 * @version v1.0
 * 
 * @2013-7-4
 * 
 */
@Controller
@RequestMapping(value = "/push/config")
public class AppChannelConfigController extends PushBaseController {

	private static final String APNS_FORM = "apns";
	private static final String APNS_SANDBOX_FORM = "apns_sandbox";
	private static final String OPENFIRE_FORM = "openfire";

	@Inject
	private AppChannelConfigService configService;

	@RequestMapping
	public String list(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			@RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize, Model model) {
		Page<AppChannelConfigVo> configs = configService.findBy(pageNumber, pageSize, QuerySpecs.EMPTY_QUERY_SPECS);
		model.addAttribute("configs", configs);
		model.addAttribute("page", new PageMustache(configs, PAGINATION_SIZE));
		return "/push/configs";
	}

	@RequestMapping(value = "delete")
	public String delete(@RequestParam("id") String appId, RedirectAttributes redirectAttributes) {
		//FIXME 如果appId使用路径参数，类似com.csair.amp的appId，传过来只com.csair，难道是SpringMVC BUG?
		this.configService.removeConfig(appId);
		redirectAttributes.addFlashAttribute("message", "删除应用配置成功 ");
		return "redirect:/push/config";
	}

	@RequestMapping(value = "channel", method = RequestMethod.GET)
	public String channelConfigsForm(@RequestParam(value = "appId", required = false) @ModelAttribute("appId") String appId,
			@RequestParam(value = "create", required = false) @ModelAttribute("create") boolean create,
			@RequestParam(value = "formType", defaultValue = "all") String formType,
			@ModelAttribute("redirect") String redirectUrl, Model model) {
		model.addAttribute("appId", appId);
		model.addAttribute("create", create);
		model.addAttribute("redirect", redirectUrl);
		if (!create) {
			Assert.notNull(appId, "appId参数不能为null");
			AppChannelConfigVo cfg = this.configService.getConfig(appId);
			model.addAttribute("apns", cfg.getApnsConfig());
			model.addAttribute("apnsSandbox", cfg.getApnsSandboxConfig());
			model.addAttribute("openfire", cfg.getOpenfireConfig());
		}
		
		model.addAttribute("create", create);
		model.addAttribute("redirect", redirectUrl);
		model.addAttribute("appId", appId);
		if (APNS_FORM.equals(formType)) {
			model.addAttribute("apnsForm", true);
		} 
		else if (APNS_SANDBOX_FORM.equals(formType)) {
			model.addAttribute("apnsSandboxForm", true);
		} 
		else if (OPENFIRE_FORM.equals(formType)) {
			model.addAttribute("openfireForm", true);
		}
		else{
			model.addAttribute("apnsForm", true);
			model.addAttribute("apnsSandboxForm", true);
			model.addAttribute("openfireForm", true);
		}
		
		return "/push/channel-configs-form";
	}

	@RequestMapping(value = "channel", method = RequestMethod.POST)
	public String channelConfig(AppChannelConfigForm form,
			@RequestParam(value = "redirect", required = false) String redirectUrl, RedirectAttributes redirectAttributes)
			throws IOException {

		updateApnsConfig(form.getApns(), form.getAppId(), false);
		updateApnsConfig(form.getApnsSandbox(), form.getAppId(), true);

		OpenfireConfigForm openfire = form.getOpenfire();
		if (openfire != null) {
			configService.setOpenfireConfig(form.getAppId(), openfire.getUsername(), openfire.getPassword());
		}

		if (StringUtils.isEmpty(redirectUrl)) {
			redirectAttributes.addFlashAttribute("message", "配置信息修改成功");
			return "redirect:/push/config";
		} else {
			redirectAttributes.addAttribute("appId", form.getAppId());
			return redirectUrl;
		}
	}
	
	private void updateApnsConfig(ApnsConfigForm apnsForm, String appId, boolean sandbox) throws IOException{
		if(apnsForm!=null){
			if (apnsForm.getCertFile() != null && apnsForm.getCertFile().getSize() != 0) {
				InputStream certIs = null;
				try {
					certIs = apnsForm.getCertFile().getInputStream();
					configService.setApnsConfig(appId, certIs, apnsForm.getCertFile().getOriginalFilename(),
							apnsForm.getCertPassword(), sandbox);
				} finally {
					IOUtils.closeQuietly(certIs);
				}
			} else {
				configService.updateApnsConfig(appId, apnsForm.getCertPassword(), sandbox);
			}
		}
	}
}
